<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Db;
use think\Config;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 1;
        $this->model = new \app\common\model\Order;
    }  
    /**
     * 生成订单
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/create_order)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     */
    public function create_order()
    {
       
        if(empty($this->user_id))$this->error('请重新登录');

        // halt($params);
        $order_detail = $this->model->order_add($this->user_id);
        $return['order_data'] = $order_detail;
        $return['Admission_notice'] = Config::get('site.Admission_notice');
        $return['name'] = Config::get('site.name');
        $return['good_name'] = Config::get('site.good_name');
       $this->success('生成订单',$return);
    }

    /**
     * 订单调起支付
     * @ApiSummary  (调起支付)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/order_pay)
     * @ApiParams   (name="order_no",type=int,required=true,description="订单号码")
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     */
    public function order_pay()
    {
       
        if(empty($this->user_id))$this->error('请重新登录');

        // halt($params);
        $order_detail = Db::name('order')->where(['order_no'=>input('order_no')])->find();
       
        // 发起微信支付
        $this->init_wx_pay_for_wxapp();
     
        $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wxapp'])->find();
    
        $payment = $this->wxapp->payment;
       
        $attributes = [
            'trade_type'       => 'JSAPI',
            'body'             => Config::get('site.name'),
            'detail'           => Config::get('site.name'),
            'out_trade_no'     => $order_detail['order_no'],
            'openid'           => $third['openid'],
            'total_fee'        => $order_detail['total_price']*100,
            'notify_url'       => Config::get('site.cdnurl').'api/order/callback_for_wxapp',
        ];

        $order_detail = new WXPAY_ORDER($attributes);
        // halt($order_detail);
        $result = $payment->prepare($order_detail);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
            return $this->success('订单创建成功,预支付成功',$config);
        }
        return $this->error('微信支付调用失败',$result);
    }
    
    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('epay');
        $options = [
            'debug'  => false,
            'log' => [
                'level' => 'debug',
                'file'  => LOG_PATH . '/tmp/easywechat.log',
            ],
            'app_id'   => $config['wechat']['miniapp_id'],// 小程序 APPID
            'secret'   => $config['wechat']['app_secret'],//小程序密钥
            'payment' => [
                'merchant_id'        =>  $config['wechat']['mch_id'],//小程序商户号
                'key'                =>  $config['wechat']['key'],//小程序支付密钥
                'notify_url'         =>  Config::get('site.cdnurl').'api/order/callback_for_wxapp',
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }

     /**
     * 小程序支付回调
     * @ApiSummary  (小程序支付回调)
     * @ApiRoute    (/api/index/callback_for_wxapp)
     */
    public function callback_for_wxapp(){
        $this->init_wx_pay_for_wxapp();
        $response = $this->wxapp->payment->handleNotify(function($notify, $successful){

            if ($successful) {
                $notify_json = json_encode($notify);
                if ($notify['return_code'] === 'SUCCESS') {
                    if($notify["result_code"] === "SUCCESS"){

                        $order_data = Db::name('order')->where(['order_no'=>$notify->out_trade_no])->find();
                       
                        $user_data = Db::name('user')->where('id',$order_data['user_id'])->find();
                        if($user_data['vip_time']){
                            
                            $new_vip_time = strtotime("+1 year",$user_data['vip_time']);
                        }else{

                            $new_vip_time = strtotime("+1 year",time());

                            // 首次充值判断 
                            if($user_data['Invitees']){
                                $invitees_data = Db::name('user')->where('id',$user_data['Invitees'])->find();

                                $invitees_vip_time = strtotime("+1 months",$invitees_data['vip_time']);

                                //有效邀请人数量 加一
                                Db::name('user')->where('id',$user_data['Invitees'])->setInc('effect_num');
                                //给邀请人的 VIP续期
                                Db::name('user')->where('id',$user_data['Invitees'])->update(['vip_time'=>$invitees_vip_time]);
                            }

                            
                        }

                        Db::name('order')->where('order_no',$notify->out_trade_no)->where('pay_status',10)->update([
                            'pay_status' => '20',
                            'pay_time' => time(),
                        ]);



                        Db::name('user')->where('id',$order_data['user_id'])->update(['vip_time'=>$new_vip_time]);

                    }
                }
            }

            return true; // 返回处理完成
            
            
        });
        $response->send();
    }

  

}
